<template>
  <div class="trade-container">
    <div style="padding: 10px;background-color: #ffffff">
      <el-select placeholder="Select" v-model="templateValue" value-key="id" size="large" style="width: 240px;margin-right: 60px" @change="templateChange">
        <el-option v-for="item in templateList.data" :key="item.id" :label="item.templateName" :value="item"/>
      </el-select>
      <el-button type="primary" @click="bulkImportClick">批量导入</el-button>
<!--      <el-button type="primary">批量导出</el-button>-->
      <el-button type="primary" @click="addPerson">新增</el-button>
      <el-button :icon="RefreshLeft" size="small" circle @click="personList(pageIndex)" />
    </div>
    <div class="quota-box" v-if="quotaData.length">
      <p>证件额度</p>
      <div class="quota-data">
        <div class="quota-data-item" v-for="item in quotaData" :key="item.id">{{item.cnName}}:{{item.certNum}}</div>
      </div>
    </div>
    <el-menu ellipsis class="el-menu-popper-demo" mode="horizontal" unique-opened :default-active="defaultActive" @select="menuSelect" style="width: 100%;margin-bottom: 20px">
      <el-menu-item index="0">已申请</el-menu-item>
      <el-menu-item index="1">一审拒绝</el-menu-item>
      <el-menu-item index="2">二审拒绝</el-menu-item>
      <el-menu-item index="3">三审拒绝</el-menu-item>
      <el-menu-item index="4">草稿箱</el-menu-item>
      <el-menu-item index="5">制证数据</el-menu-item>
    </el-menu>
    <div>
      <div style="margin-bottom: 10px">
        <span style="padding-right: 20px">共{{pageTotal}}条</span>
        <span>选择{{selectList.data.length}}条</span>
      </div>
      <div style="margin-bottom: 10px" v-show="defaultActive === '4'">
        <el-button type="primary" @click="checkAllApply">提交审核</el-button>
        <el-button style="margin-left: 10px" type="danger" @click="delAll">删除</el-button>
      </div>
      <div style="margin-bottom: 10px" v-show="defaultActive === '0'">
        <el-button style="margin-left: 10px" type="danger" @click="delAllRefuse">批量删除</el-button>
      </div>
      <el-table ref="multipleTable"
                :data="tableData.data"
                tooltip-effect="dark"
                stripe
                highlight-selection-row
                max-height="750"
                style="width: 100%"
                @selection-change="handleSelectionChange">
        <el-table-column type="index" />
        <el-table-column  fixed="left" type="selection" width="55" v-if="defaultActive === '4'||defaultActive === '0'" />
        <el-table-column prop="uuId" label="批次号" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column v-for="item in templateValue.fieldTemplateList" :key="item.id" :prop="'value.'+item.fieldName" :label="item.notes" width="120" show-overflow-tooltip>
          <template #default="scope" v-if="item.fieldName === 'faceImg'">
            <img v-lazy="scope.row.value[item.fieldName]" v-show="scope.row.value[item.fieldName]" style="width: 30px;height: 30px" :src="scope.row.value[item.fieldName]" alt="#">
          </template>
<!--          <template #default="scope" v-if="item.fieldName === 'gender'">{{scope.row.value[item.fieldName] === 0 ? '男' : '女'}}</template>-->
        </el-table-column>
        <el-table-column prop="state" label="证件状态" fixed="right" width="100">
          <template #default="scope">{{checkStatusFormattingState(scope.row.state)}}</template>
        </el-table-column>
        <el-table-column prop="bsState" label="审核状态" width="100">
          <template #default="scope">{{checkStatusBS(scope.row.bsState)}}</template>
        </el-table-column>
        <el-table-column prop="oneLevelState" label="一级状态" width="100">
          <template #default="scope">{{checkStatusFormatting(scope.row.oneLevelState)}}</template>
        </el-table-column>
        <el-table-column prop="twoLevelState" label="二级状态" width="100">
          <template #default="scope">{{checkStatusFormatting(scope.row.twoLevelState)}}</template>
        </el-table-column>
        <el-table-column prop="threeLevel" label="三级状态" width="100">
          <template #default="scope">{{checkStatusFormatting(scope.row.threeLevel)}}</template>
        </el-table-column>
        <el-table-column prop="remark" label="拒绝理由" width="100">
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-link type="primary" style="margin-right: 10px" @click="lookDetails(scope.row.id)">查看</el-link>
            <div style="display: inline-block" v-if="defaultActive !== '5'">
              <el-link type="primary" style="margin-right: 10px" @click="resetSubmit(scope.row.id)" v-if="scope.row.oneLevelState === '2' || scope.row.twoLevelState === '2' ||scope.row.threeLevel === '2'">重新提交</el-link>
              <el-link type="primary" v-if="scope.row.state === '1'||scope.row.oneLevelState === '2' || scope.row.twoLevelState === '2' ||scope.row.threeLevel === '2'" @click="editInfo(scope.row.id)">修改</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 30px">
        <el-pagination background layout="prev, pager, next" :page-size="100" :total="pageTotal" @current-change="currentChange"/>
      </div>

    </div>
  </div>
  <personDetails v-if="showDetails" :type="templateValue.cert.type" :personId="personId" :templateId="templateValue.id" @showDetailsPersonEmit="showDetailsPersonEmit"></personDetails>
</template>

<script setup>
import {ref, reactive, computed} from "vue";
import {
  _checkAllApply, _delAll, _delAllRefuse,
  _getCardTypeSet,
  _getTemplateList,
  _personList, _resetState,
  _updatePerson
} from "../../http/api.js";
import {useRouter} from "vue-router";
import {ElLoading, ElMessage, ElMessageBox, ElNotification} from "element-plus";
import personDetails from './personDetails.vue'
import {RefreshLeft} from "@element-plus/icons-vue";
import {checkStatusFormattingState, checkStatusFormatting, checkStatusBS} from "../../utils/index.js"

const router = useRouter();
let loginId = '';
let exhibitionId = '';
let oneFlag = '';
let twoFlag = '';
let threeFlag = '';
let t = setInterval(() => {
  loginId = sessionStorage.getItem('loginId');
  exhibitionId = sessionStorage.getItem('projectId');
  oneFlag = sessionStorage.getItem('oneFlag');
  twoFlag = sessionStorage.getItem('twoFlag');
  threeFlag = sessionStorage.getItem('threeFlag');
  if(loginId&&exhibitionId) {
    clearInterval(t);
    getTemplateList();
  }
},200)
const templateValue = ref({});
const templateList = reactive({ // 模板列表
  data:[]
})
const tableData = reactive({ // 表格数据
  data:[]
})
const showDetails = ref(false);//弹框
const personId = ref();//人员id
const pageTotal = ref(); // 总数
let pageIndex = ref(1);
const quotaData = ref([]); // 额度数据
const defaultActive = ref('0'); // 默认显示的菜单数据
const selectList = reactive({ // 选择的表格数据
  data:[]
})

// 处理缓存
let defaultActiveOld = sessionStorage.getItem('defaultActive');
if(defaultActiveOld) {
  defaultActive.value = defaultActiveOld;
}



// 处理空对象
const disposeNullObj = (obj) => {
  let params = { ... obj };
  for (const key in params) {
    if(!params[key]) {
      delete params[key]
    }
  }
  return params;
}

// 数据选择
const handleSelectionChange = (item) => {
  console.log(item);
  selectList.data = item;
}
//获取模板数据
const getTemplateList = () => {
  templateList.data = [];
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'});
  _getTemplateList()
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          let list = res.data.data;
          getCardTypeSet(list)
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
      })
}
// 获取用户对应证件列表
const getCardTypeSet = (list) => {
  console.log(list);
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'});
  _getCardTypeSet(loginId)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          let cardTypeList = res.data.data;
          for (let i = 0; i < list.length; i++) {
            if(!list[i].cert) {
              continue;
            }
            for (let j = 0; j < cardTypeList.length; j++) {
              if(list[i].cert.id === cardTypeList[j].certId) {
                if(cardTypeList[j].typeName === '人证') {
                  templateList.data.push(list[i]);
                  quotaData.value.push(cardTypeList[j])
                }
              }
            }
          }
          if(templateList.data.length) {
            let templateValueOld = sessionStorage.getItem('templateValue');
            if(templateValueOld) {
              let valueOld = JSON.parse(templateValueOld);
              let newValue = {};
              templateList.data.forEach(v => {
                if(v.id === valueOld.id) {
                  newValue = v;
                }
              })
              templateValue.value = newValue;
            }else{
              templateValue.value = templateList.data[0];
            }
            personList(pageIndex.value);
          }
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
      })
}
// 模板切换
const templateChange = (item) => {
  console.log(item);
  sessionStorage.setItem('templateValue',JSON.stringify(item));
  personList(pageIndex.value);
}
// 处理state字段
const disposeState = () => {
  let state = '0';
  if(defaultActive.value === '4') {
    state = '1'
  }
  if(defaultActive.value === '5') {
    state = '2,3,4,5'
  }
  return state
}
// 获取人员列表
const personList = (pageIndex) => {
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'});
  let params = {
    current: pageIndex,
    size: 100,
    userId: loginId,
    exhibitionId,
    templateId: templateValue.value.id,
    state: disposeState(),

    oneLevelState: defaultActive.value === '1' ? '2':'',
    twoLevelState: defaultActive.value === '2' ? '2':'',
    threeLevel: defaultActive.value === '3' ? '2':'',
  }
  if(oneFlag === 'true' && twoFlag === 'true' && threeFlag === 'true') {
    delete params.userId
  }
  params = disposeNullObj(params)
  _personList(params)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          let item = res.data.data;
          pageTotal.value = item.total;
          let records = res.data.data.records;
          tableData.data = records;
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
      })
}
// 新增人员点击
const addPerson = () => {
  console.log(templateValue.value);
  if(!templateValue.value.id) return ElMessage({message: '请选择证件类型', type: 'warning' });
  router.push({ path: '/index/addPerson',query:{ templateId: templateValue.value.id,type:templateValue.value.cert.type }})
}
// 修改人员信息
const editInfo = (id) => {
  if(!templateValue.value.id) return ElMessage({message: '请选择证件类型', type: 'warning' });
  router.push({ path: '/index/addPerson',query:{ templateId: templateValue.value.id,personId:id,type:templateValue.value.cert.type,editTow:true }})
}
// 重新提交
const resetSubmit = (id) => {
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'});
  _resetState({id})
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          ElMessage({message: '提交成功', type: 'success' });
          personList(pageIndex.value);
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
        ElMessage({message: '网络异常，请重试', type: 'error' });
      })
}
// 分页点击
const currentChange = (index) => {
  personList(index);
}
// 菜单选择
const menuSelect = (item) => {
  console.log(item);
  defaultActive.value = item;
  sessionStorage.setItem('defaultActive',item)
  personList(pageIndex.value);
}

// 查看详情
const lookDetails = (id) => {
  personId.value = id;
  showDetails.value = true;
}
// 监听详情弹框
const showDetailsPersonEmit = () => {
  showDetails.value = false;
}

// 批量导入点击
const bulkImportClick = () => {
  router.push({ path: '/index/importData'})
}

// 批量提交审核
const checkAllApply = () => {
  if(!selectList.data.length) return ElMessage({message: '请选择需要提交的数据', type: 'warning' });
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'});
  let arr = [];
  selectList.data.forEach(v => {
    arr.push({id:v.id,type:templateValue.value.cert.type,enType:templateValue.value.cert.enName,userId: loginId,templateId: templateValue.value.id})
  })
  console.log(arr);
  _checkAllApply(arr)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          selectList.data = [];
          ElMessage({message: '提交成功', type: 'success' });
          personList(pageIndex.value);
        }else {
          ElMessage({message: res.data.msg, type: 'warning' });
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
        ElMessage({message: '网络异常，请重试', type: 'error' });
      })
}
// 批量删除
const delAll = () => {
  if(!selectList.data.length) return ElMessage({message: '请选择需要提交的数据', type: 'warning' });
  ElMessageBox.confirm('确定删除?', '提示', {confirmButtonText: 'OK', cancelButtonText: 'Cancel', type: 'warning',})
      .then(() => {
        const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'});
        let arr = [];
        selectList.data.forEach(v => {
          arr.push(v.id)
        })
        console.log(arr);
        _delAll(arr)
            .then(res => {
              console.log(res);
              loading.close();
              if(res.data.ok) {
                selectList.data = [];
                ElMessage({message: '删除成功', type: 'success' });
                personList(pageIndex.value);
              }
            })
            .catch(err => {
              console.log(err);
              loading.close();
              ElMessage({message: '网络异常，请重试', type: 'error' });

            })
      })
      .catch(() => {})
}
// 批量删除拒绝
const delAllRefuse = () => {
  if(!selectList.data.length) return ElMessage({message: '请选择需要提交的数据', type: 'warning' });
  ElMessageBox.confirm('确定删除?', '提示', {confirmButtonText: 'OK', cancelButtonText: 'Cancel', type: 'warning',})
      .then(() => {
        let arr = [];
        selectList.data.forEach(v => {
          if((v.oneLevelState === '2' || v.threeLevel === '2' || v.twoLevelState === '2') && v.state === '0') {
            arr.push({id:v.id,userId:loginId})
          }
        })
        if(arr.length === 0) return ElMessage({message: '没有可操作的数据', type: 'warning' });
        const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'});
        _delAllRefuse(arr)
            .then(res => {
              console.log(res);
              loading.close();
              if(res.data.ok) {
                selectList.data = [];
                ElMessage({message: '删除成功', type: 'success' });
                personList(pageIndex.value);
              }else{
                ElMessage({message: res.data.msg, type: 'warning' });
              }
            })
            .catch(err => {
              console.log(err);
              loading.close();
              ElMessage({message: '网络异常，请重试', type: 'error' });
            })
      })
      .catch(() => {})
}
</script>

<style lang="scss" scoped>
.trade-container{
  padding: 10px;
  .quota-box{
    padding: 10px;
    background-color: #ffffff;
    p{
      font-weight: bold;
      margin-bottom: 10px;
    }
    .quota-data{
      display: flex;
      flex-wrap: wrap;
      .quota-data-item{
        margin-right: 30px;
      }
    }
  }
}
.icon-style{
  font-size: 24px;
  cursor: pointer;
}
.face-img-box{
  width: 50px;
  height: 65px;
}
</style>
